package com.company.project.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.company.project.common.utils.DataResult;
import com.company.project.common.utils.Func;
import com.company.project.common.utils.StringUtil;
import com.company.project.common.utils.excel.ExcelUtils;
import com.company.project.entity.*;
import com.company.project.mapper.*;
import com.company.project.service.*;
import com.company.project.vo.req.TSeatsEntityOperationReqVO;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.math.BigDecimal;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;


@Service("tWdkhService")
public class TWdkhServiceImpl extends ServiceImpl<TWdkhMapper, TWdkhEntity> implements TWdkhService {

    @Resource
    private TWdkhMapper wdkhMapper;
    @Resource
    private TGhszMapper tGhszMapper;
    @Resource
    private TGhkhMapper ghkhMapper;
    @Resource
    private UserService userService;
    @Resource
    private SysDeptMapper sysDeptMapper;
    @Resource
    private HttpSessionService httpSessionService;

    @Resource
    private TSeatsMapper seatsMapper;
    @Resource
    private TGjjlMapper tGjjlMapper;
    @Resource
    private YhCallService yhCallService;
    @Resource
    private TSeatsMapper tSeatsMapper;
    @Resource
    private TGzszMapper gzszMapper;
    @Resource
    private RoleService roleService;
    @Resource
    private TGjjlService tGjjlService;

    @Override
    public DataResult zhuanyi(TWdkhEntity tWdkh) {
        List<String> ids = tWdkh.getIds();
        wdkhMapper.updateUsername(ids,tWdkh.getUsername());
        wdkhMapper.updateSsxs(ids,tWdkh.getUsername());
        return DataResult.success();
    }

    @Override
    public DataResult rlgh(Map<String,Object> map) {
        List<String> ids = (List<String>) map.get("ids");
        String ssghid = String.valueOf(map.get("ghmc"));//公海id
        TGhszEntity tGhszEntity1 = tGhszMapper.selectById(ssghid);
        for (String id : ids) {
            TWdkhEntity wdkh = wdkhMapper.selectById(id);
            TGhkhEntity ghkh = new TGhkhEntity();
            ghkh.setKhname(wdkh.getKhname());
            ghkh.setLxr(wdkh.getLxr());
            ghkh.setLxdh(wdkh.getLxdh());
            ghkh.setSsxs("");
            ghkh.setKhjb(wdkh.getKhjb());
            ghkh.setQdcs(wdkh.getQdcs());
            ghkh.setGjjl(wdkh.getGjjl());
            ghkh.setZhgjtime(wdkh.getZhgjtime());
            ghkh.setRktime(new Date());
            ghkh.setKhly(wdkh.getKhly());
            ghkh.setRghyy("主动放弃");
            ghkh.setSsgh(tGhszEntity1.getGhmc());
            ghkh.setWdkhid(id);
            ghkh.setSsghid(ssghid);
            ghkhMapper.insert(ghkh);
        }
        SysUser userInfo = userService.getUserInfo();
        TSeatsEntity tSeatsEntity = seatsMapper.selectOne(Wrappers.<TSeatsEntity>lambdaQuery()
                .eq(TSeatsEntity::getAccountid, userInfo.getId()));
        TGhszEntity tGhszEntity = tGhszMapper.selectList(Wrappers.<TGhszEntity>lambdaQuery().eq(TGhszEntity::getId, ssghid).eq(TGhszEntity::getSsgs, tSeatsEntity.getCorporatename())).get(0);
        //变更客户数量
        tGhszEntity.setKhsl(tGhszEntity.getKhsl() + ids.size());
        tGhszMapper.updateById(tGhszEntity);
        wdkhMapper.rlgh((List<String>) map.get("ids"));
        return DataResult.success();
    }

    @Override
    public DataResult saveFile(MultipartFile multipartFile) {
        String khnameList = "";
        SysUser userInfo = userService.getUserInfo();
        TSeatsEntity tSeatsEntity = seatsMapper.selectOne(Wrappers.<TSeatsEntity>lambdaQuery()
                .eq(TSeatsEntity::getAccountid, userInfo.getId()));
        Date hlDay = new Date();
        //根据公司名称查询规则
        TGzszEntity tGzszEntity = gzszMapper.selectOne(Wrappers.<TGzszEntity>lambdaQuery().eq(TGzszEntity::getSsgs, tSeatsEntity.getCorporatename()));
        //
        Integer wcjhl = tGzszEntity.getWcjhl();//未成交回流
        Integer wgjhl = tGzszEntity.getWgjhl();//未跟进回流
        Date lrgh2 = new Date();
        if (wcjhl > 0 && wgjhl > 0){
            //设置流入公海时间  未成交回流   入库时间加上设置时间
            Calendar calendar2 = Calendar.getInstance();
            calendar2.setTime(lrgh2);
            //加上规定时间
            calendar2.add(Calendar.DAY_OF_MONTH, wcjhl);
            lrgh2 = calendar2.getTime();
            Date lrgh = new Date();

            //设置流入公海时间  未跟进回流
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(lrgh);
            //加上规定时间
            calendar.add(Calendar.DAY_OF_MONTH, wgjhl);
            lrgh = calendar.getTime();
            hlDay = lrgh.compareTo(lrgh2) > 0 ? lrgh2 : lrgh;
        } else {
            hlDay = null;
        }
        try {
            JSONArray objects = ExcelUtils.readMultipartFile(multipartFile);
            List<Map<String,String>> javaObject = JSONArray.toJavaObject(objects, List.class);
            for(Map<String,String> map: javaObject) {
                String khname = map.get("*客户名称");
                String lxr = map.get("联系人");
                String lxdh = map.get("*联系电话");
                if (StringUtil.isNotBlank(lxdh)) {
                    String sple = "";
                    if (("" + lxdh).contains("，")){//13731151953，18631169798，13785112016
                        sple = "，";
                    } else if (("" + lxdh).contains("；")){
                        sple = "；";
                    } else if (("" + lxdh).contains(";")){
                        sple = ";";
                    } else if (("" + lxdh).contains(",")) {//13731151953，18631169798，13785112016
                        sple = ",";
                    }
                    if (StringUtil.isNotBlank(sple)) {
                        String[] l = lxdh.split(sple);
                        lxdh = l[0].toString();
                        if (!lxdh.contains("-"))  { //0311-88708100
                            BigDecimal bd = new BigDecimal("" + lxdh);
                            lxdh = bd.toBigInteger().toString();
                        }
                    }
                    if (!lxdh.contains("-")) {
                        //  判断是否为科学计数法（包含E、e、+等符号）
                        BigDecimal bd1 = new BigDecimal("" + lxdh);
                        lxdh = bd1.toBigInteger().toString();
                    }
                }
                String qtdh = map.get("其他手机号（多个手机号用;隔开）");
                if (StringUtil.isNotBlank(qtdh)) {
                    String sple = "";
                    if (("" + qtdh).contains("，")){//13731151953，18631169798，13785112016
                        sple = "，";
                    } else if (("" + qtdh).contains("；")){
                        sple = "；";
                    } else if (("" + qtdh).contains(";")){
                        sple = ";";
                    } else if (("" + qtdh).contains(",")) {//13731151953，18631169798，13785112016
                        sple = ",";
                    }

                    if (StringUtil.isNotBlank(sple)) {
                        String[] l = qtdh.split(sple);
                        qtdh = "";
                        for (int i = 0; l.length > i; i++) {
                            if (l[i].indexOf("-") > -1)  { //0311-88708100
                                qtdh += l[i].toString() + ";";
                            } else {
                                if (phoneValidate(l[i])){
                                    BigDecimal bd = new BigDecimal("" + l[i]);
                                    qtdh += bd.toBigInteger().toString() + ";";
                                }
                            }
                        }
                        if (qtdh.length()>1){
                            qtdh = qtdh.substring(0, qtdh.length() - 1);
                        }
                    } else if (qtdh.indexOf("-") < -1) {
                        BigDecimal bd = new BigDecimal("" + qtdh);
                        qtdh = bd.toBigInteger().toString() + ";";
                    }
                }
                String khjb = map.get("客户级别");
                String khly = map.get("客户来源");
                String khdz = map.get("客户地址");
                String khhy = map.get("客户行业");
                String bz = map.get("备注");
                if (Func.isEmpty(khjb)) {
                    khjb = "0";
                }
                //已存在的客户名称不在入库
                Long aLong = wdkhMapper.selectCount(Wrappers.<TWdkhEntity>lambdaQuery()
                        .eq(TWdkhEntity::getKhname, khname)
                        .eq(TWdkhEntity::getSsxs,userInfo.getUsername()));
                if (aLong > 0 || Func.isEmpty(khname)) {
                    khnameList += "客户名称(已存在):" + khname + ";";
                    continue;
                }
                //效验联系电话是否正确
                if (!phoneValidate(lxdh) || Func.isEmpty(lxdh)) {
                    khnameList += "联系电话(格式异常):" + lxdh + ";";
                    continue;
                }

                TWdkhEntity wdkh = new TWdkhEntity();
                wdkh.setKhname(khname);
                wdkh.setLxr(lxr);
                wdkh.setLxdh(lxdh);
                wdkh.setQtdh(qtdh);
                wdkh.setKhly(khly);
                wdkh.setKhjb(khjb);
                wdkh.setKhdz(khdz);
                wdkh.setKhhy(khhy);
                wdkh.setBz(bz);

                wdkh.setUsername(userInfo.getUsername());//负责人
                wdkh.setSsxs(userInfo.getUsername());//所属销售
                wdkh.setRktime(new Date());
                wdkh.setCompany(tSeatsEntity.getCorporatename());
                wdkh.setIsrlgh("1");
                wdkh.setIsbd("0");
                wdkh.setQdcs(0);
                wdkh.setIscj("0");//
                wdkh.setLrghtime(hlDay);
                //添加入库
                save(wdkh);
            }
        }catch (RuntimeException e) {
            e.printStackTrace();
            return DataResult.fail(e.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            return DataResult.fail("上传失败！");
        }
        return DataResult.success(khnameList);
    }
    //校验手机号
    public boolean phoneValidate(String phoneNumber){
        if (phoneNumber.equals("-")) return true;
        if (StringUtil.isNotBlank(phoneNumber) && !phoneNumber.isEmpty()){
            return Pattern.matches(
                    "^1[3-9]{1}\\d{9}$|" +
                            "^0\\d{3}-\\d{8}$|" +
                            "^0\\d{3}-\\d{7}$|" +
                            "^0\\d{2}-\\d{7}$|" +
                            "^0\\d{2}-\\d{8}$", phoneNumber);
        }
        return false;
    }

    @Override
    public DataResult infoData() {
        //通过用户 部门 递归查询部门id 再反查 我的客户表
        try {
            String userId = httpSessionService.getCurrentUserId();
            SysUser sysUser = userService.getById(userId);

            SysDept sysDept = sysDeptMapper.selectOne(Wrappers.<SysDept>lambdaQuery()
                    .eq(SysDept::getId, sysUser.getDeptId()));
            TSeatsEntity tSeatsEntity = tSeatsMapper.selectOne(Wrappers.<TSeatsEntity>lambdaQuery().eq(TSeatsEntity::getAccountid, sysUser.getId()));
            List<SysDept> deptList = new ArrayList<>();
            if (Func.equals("D000000",sysDept.getDeptNo())) {
                deptList = sysDeptMapper.selectList(Wrappers.<SysDept>lambdaQuery());
            } else {
                deptList = sysDeptMapper.selectList(Wrappers.<SysDept>lambdaQuery().like(SysDept::getRelationCode, sysDept.getDeptNo()));
            }
            TGzszEntity tGzszEntity = gzszMapper.selectOne(Wrappers.<TGzszEntity>lambdaQuery().eq(TGzszEntity::getSsgs, tSeatsEntity.getCorporatename()));

            Map<String, Object> map = new HashMap<>();
            //请选择客户来源、请选择意向度、请选择所属销售 username;
            List<String> username = wdkhMapper.selectUsername(sysDept.getDeptNo(),sysUser);
//            List<String> khly = wdkhMapper.selectKuly(sysDept.getDeptNo());
            //客户来源:搜索引擎、社交媒体、广告投放、客户推荐、展会资源、上门、个人资源、等等,或者支持自定义标签,让客户自己设置各自的;
            List<String> khly = new ArrayList<>();
            khly.add("搜索引擎");
            khly.add("社交媒体");
            khly.add("广告投放");
            khly.add("客户推荐");
            khly.add("展会资源");
            khly.add("上门");
            khly.add("个人资源");
            khly.add("特殊来源");
            khly.add("专属来源");
            khly.add("其他来源");
            List<Map<String,String>> hkjb = new ArrayList<>();
            Map<String,String> mapin = new HashMap<>();
            mapin.put("id","A");
            mapin.put("value","A:高意向客户:近7天能成交客户");
            hkjb.add(mapin);
            mapin = new HashMap<>();
            mapin.put("id","B");
            mapin.put("value","B:意向客户:近30天内可能成交客户");
            hkjb.add(mapin);
            mapin = new HashMap<>();
            mapin.put("id","C");
            mapin.put("value","C:目标客户:客户本身符合产品需求,用着竞品或者有需求最近不考虑购买的客户");
            hkjb.add(mapin);
            mapin = new HashMap<>();
            mapin.put("id","D");
            mapin.put("value","D:未明确客户:就是客户需求模糊 不能判定是不是目标客户");
            hkjb.add(mapin);
            mapin = new HashMap<>();
            mapin.put("id","E");
            mapin.put("value","E:明确拒绝客户或其他情况");
            hkjb.add(mapin);
            mapin = new HashMap<>();
            mapin.put("id","0");
            mapin.put("value","0类:即刚入库默认状态类别");
            hkjb.add(mapin);
            List<String> ssxs = wdkhMapper.selectSsxs(sysDept.getDeptNo(),sysUser);
            List<TGhszEntity> tGhszEntities = tGhszMapper.selectList(Wrappers.<TGhszEntity>lambdaQuery()
                    .select(TGhszEntity::getGhmc,TGhszEntity::getId)
                    .like(TGhszEntity::getGhcy,userId)
                    .or()
                    .like(TGhszEntity::getGhgly,userId)
                    .or()
                    .like(TGhszEntity::getGhcybm,sysDept.getId()));
            map.put("username",username);
            map.put("khly",khly);
            map.put("hkjb",hkjb);
            map.put("ssxs",ssxs);
            map.put("dept",deptList);
            map.put("gh",tGhszEntities);
            //是否隐藏
            List<SysRole> roleInfoByUserId = roleService.getRoleInfoByUserId(userId);
            List<String> collect = roleInfoByUserId.stream().map(e -> e.getName()).collect(Collectors.toList());
            if (Func.isNotEmpty(tGzszEntity)) {
                if (collect.contains("员工") || collect.contains("主管")) {
                    map.put("isyc", tGzszEntity.getIsyc());
                }
            }
            return DataResult.success(map);
        } catch (Exception e) {
            e.printStackTrace();
            return DataResult.fail("初始化选项失败，请联系管理员！");
        }
    }

    @Override
    public DataResult add(TWdkhEntity tWdkh) {
        //通过access_token拿userId
        String userId = httpSessionService.getCurrentUserId();
        TSeatsEntity tSeatsEntity = seatsMapper.selectOne(Wrappers.<TSeatsEntity>lambdaQuery()
                .eq(TSeatsEntity::getAccountid, userId));
        SysUser userInfo = userService.getUserInfo();

        //已存在的客户名称不在入库
        Long aLong = wdkhMapper.selectCount(Wrappers.<TWdkhEntity>lambdaQuery().eq(TWdkhEntity::getKhname, tWdkh.getKhname()));
        if (aLong > 0 || Func.isEmpty(tWdkh.getKhname())) {
            return DataResult.fail("客户名称(已存在):"+tWdkh.getKhname());
        }
        //效验联系电话是否正确
        if(!phoneValidate(tWdkh.getLxdh()) || Func.isEmpty(tWdkh.getLxdh())) {
            return DataResult.fail("联系电话(格式异常):"+tWdkh.getLxdh() +";");
        }
        //根据公司名称查询规则
        TGzszEntity tGzszEntity = gzszMapper.selectOne(Wrappers.<TGzszEntity>lambdaQuery().eq(TGzszEntity::getSsgs, tSeatsEntity.getCorporatename()));
        //
        Integer wcjhl = tGzszEntity.getWcjhl();//未成交回流
        Integer wgjhl = tGzszEntity.getWgjhl();//未跟进回流
        Date lrgh2 = new Date();
        if (wcjhl > 0 && wgjhl > 0){
            //设置流入公海时间  未成交回流   入库时间加上设置时间
            Calendar calendar2 = Calendar.getInstance();
            calendar2.setTime(lrgh2);
            //加上规定时间
            calendar2.add(Calendar.DAY_OF_MONTH, wcjhl);
            lrgh2 = calendar2.getTime();
            Date lrgh = new Date();

            //设置流入公海时间  未跟进回流
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(lrgh);
            //加上规定时间
            calendar.add(Calendar.DAY_OF_MONTH, wgjhl);
            lrgh = calendar.getTime();
            Date hlDay = lrgh.compareTo(lrgh2) > 0 ? lrgh2 : lrgh;

            tWdkh.setLrghtime(hlDay);
        }

        tWdkh.setUsername(userInfo.getUsername());//负责人
        tWdkh.setSsxs(userInfo.getUsername());//所属销售
        tWdkh.setRktime(new Date());
        tWdkh.setCompany(tSeatsEntity.getCorporatename());
        tWdkh.setIsrlgh("1");
        tWdkh.setIsbd("0");
        tWdkh.setQdcs(0);
//        自动查重功能：新建客户如果目前库中已有此客户名称则新建不成功，提示此客户已存在。
        Long integer = wdkhMapper.selectCount(Wrappers.<TWdkhEntity>lambdaQuery()
                .eq(TWdkhEntity::getKhname, tWdkh.getKhname()));
        if (integer > 0) DataResult.fail("新建不成功，客户已存在!");
        boolean save = save(tWdkh);
        return DataResult.success();
    }

    @Override
    public DataResult lingqu(TWdkhEntity tWdkh) {
        //通过access_token拿userId
        String userId = httpSessionService.getCurrentUserId();
        SysUser user = userService.getById(userId);
        TSeatsEntity tSeatsEntity = seatsMapper.selectOne(Wrappers.<TSeatsEntity>lambdaQuery()
                .eq(TSeatsEntity::getAccountid, userId));
        tWdkh.setUsername(user.getUsername());//负责人
        tWdkh.setSsxs(user.getUsername());//所属销售
        updateById(tWdkh);
        return DataResult.success();
    }

    @Override
    public DataResult getDataById(String wdkhId) {
        Map<String,Object> map = new HashMap<>();
        TWdkhEntity tWdkhEntity = wdkhMapper.selectById(wdkhId);
        List<TGjjlEntity>  tGjjlEntityList = tGjjlMapper.selectListByWhtjId(wdkhId);
        map.put("wdkh",tWdkhEntity);
        map.put("gjjl",tGjjlEntityList);
        return DataResult.success(map);
    }

    @Override
    public DataResult outbound(TWdkhEntity tWdkh) {
        String hjType = tWdkh.getHjType();//呼叫l类型  0主要号码 1其他号码
        //拨打电话后逻辑
        TWdkhEntity tWdkhEntity = wdkhMapper.selectById(tWdkh.getId());
        tWdkhEntity.setZhgjtime(new Date());
        tWdkhEntity.setIsbd("1");
        tWdkhEntity.setQdcs(tWdkhEntity.getQdcs()+1);
        wdkhMapper.updateById(tWdkhEntity);
        TGjjlEntity tGjjl = new TGjjlEntity();
        tGjjl.setXs(tWdkhEntity.getSsxs());
        tGjjl.setWhtime(new Date());
        tGjjl.setWdkhid(tWdkhEntity.getId());
        tGjjlService.save(tGjjl);
        TSeatsEntityOperationReqVO vo = new TSeatsEntityOperationReqVO();
        vo.setPhoneWH(tWdkh.getLxdh());
        return yhCallService.outbound(vo);
    }

    @Override
    public IPage<TWdkhEntity> pageKhcc(Page page, TWdkhEntity tWdkh) {
        //通过access_token拿userId
        String userId = httpSessionService.getCurrentUserId();
        TSeatsEntity tSeatsEntity = seatsMapper.selectOne(Wrappers.<TSeatsEntity>lambdaQuery()
                .eq(TSeatsEntity::getAccountid, userId));
        tWdkh.setCompany(tSeatsEntity.getCorporatename());
        return wdkhMapper.pageKhcc(page, tWdkh);
    }
}